<template>
  <div class="member-container">
    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :inline="true" :model="memberSearchModel" class="demo-form-inline" ref="memberSearchForm">
        <el-form-item label="姓名：" prop="name">
          <el-input
              v-model="memberSearchModel.name"
              placeholder="请输入姓名"
              :prefix-icon="Search"
              class="search-input"
          />
        </el-form-item>

        <el-form-item label="性别：" prop="gender">
          <el-select
              v-model="memberSearchModel.gender"
              empty-values="[null]"
              clearable
              style="width: 100px"
              class="search-select"
          >
            <el-option label="请选择" value=""/>
            <el-option label="男" value="M"/>
            <el-option label="女" value="F"/>
          </el-select>
        </el-form-item>

        <el-form-item label="出生日期" prop="birthdayRange">
          <el-date-picker
              type="daterange"
              placeholder="-"
              start-placeholder="日期从"
              end-placeholder="日期止"
              v-model="memberSearchModel.birthdayRange"
              value-format="YYYY-MM-DD"
              class="search-date"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <el-button type="primary" :icon="CirclePlus" @click="add" class="action-btn add-btn">新增</el-button>
      <el-button type="primary" :icon="Edit" @click="edit" class="action-btn edit-btn">修改</el-button>
      <el-button type="danger" :icon="Delete" @click="remove" class="action-btn delete-btn">删除</el-button>
      <el-button type="primary" :icon="Search" @click="searchAll()" class="action-btn search-btn">查询</el-button>
      <el-button type="primary" :icon="RefreshRight" @click="reset" class="action-btn reset-btn">重置</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table
          :data="members"
          height="100%"
          style="width: 100%"
          stripe
          border
          class="table-grid"
          @row-click="tblRowClick"
          ref="tblRef"
          :row-class-name="tableRowClassName"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="id" label="ID" width="150" fixed/>
        <el-table-column prop="avatar" label="头像" width="100">
          <template #default="scope">
            <div
                v-if="scope.row.avatar"
                class="rowImg"
                :style="'background-image: url('+scope.row.avatar+')'"
            ></div>
            <div
                v-else
                class="rowImg"
                style="background-image: url('https://via.placeholder.com/60')"
            ></div>
          </template>
<!--          <template #default="scope">
            <div class="rowImg" :style="'background-image: url('+(baseUrl+scope.row.avatar)+')'"></div>
          </template>-->
        </el-table-column>
        <el-table-column prop="name" label="姓名" width="155" fixed/>
        <el-table-column prop="gender" label="性别" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.gender==='M'" type="primary" class="gender-tag male">男</el-tag>
            <el-tag v-else type="danger" class="gender-tag female">女</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="membershipType" label="会员属性" width="170">
          <template #default="scope">
            <el-tag v-if="scope.row.membershipType==='VIP'" type="danger" class="vip-tag">VIP</el-tag>
            <el-tag v-else type="info" class="normal-tag">普通</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="180">
          <template #default="scope">
            <el-tag v-if="scope.row.status===1" type="primary" class="status-tag active">在会</el-tag>
            <el-tag v-else type="danger" class="status-tag inactive">退会</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="birthDate" label="出生日期" width="155"/>
        <el-table-column prop="joinDate" label="入会日期" width="155"/>
        <el-table-column prop="email" label="邮箱" width="230"/>
        <el-table-column prop="phone" label="手机号" width="175"/>
        <el-table-column prop="balance" label="账户余额" width="180">
          <template #default="scope">
            ¥{{ Number(scope.row.balance).toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" align="center" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click.stop="editRow(scope.row)" class="table-btn edit">编辑</el-button>
            <el-button type="danger" size="small" @click.stop="removeRow(scope.row)" class="table-btn delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="memberPi.pageNo"
          v-model:page-size="memberPi.pageSize"
          :page-sizes="[10, 20, 30, 40,50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="memberPi.total"
          class="member-pi"
          @change="memberPiChange"
          background=true
      />
    </div>

    <!-- 添加/修改对话框 -->
    <el-dialog
        v-model="memberDlgShow"
        :title="memberDlgTitle"
        width="600px"
        :close-on-click-modal="false"
        draggable
        show-close
        align-center
        @close="resetMemberForm"
        class="member-dialog"
    >
      <el-form
          label-width="100"
          label-position="right"
          :model="memberModel"
          ref="memberForm"
          :rules="rules"
          class="member-form"
      >
        <el-row>
          <el-col :span="14">
            <el-form-item label="姓名" prop="name">
              <el-input placeholder="请输入姓名" v-model="memberModel.name"></el-input>
            </el-form-item>
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="memberModel.gender" class="gender-radio">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请输入会员出生日期"
                  v-model="memberModel.birthDate"
              />
            </el-form-item>
            <el-form-item label="入会日期" prop="joinDate">
              <el-date-picker
                  type="date"
                  value-format="YYYY-MM-DD"
                  placeholder="请输入入会日期"
                  v-model="memberModel.joinDate"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-upload
                class="avatar-uploader"
                action="/api/members/avatar"
                :on-success="handleAvatarSuccess"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
            >
              <div
                  v-if="memberModel.avatar"
                  class="avatar-img"
                  :style="'background-image: url('+(memberModel.avatar)+')'"
              ><div class="avatar-overlay">
                <el-icon class="edit-icon"><Edit /></el-icon>
              </div></div>
              <div v-else class="avatar-placeholder">
                <el-icon class="upload-icon"><Plus /></el-icon>
                <span class="upload-text">点击上传头像</span>
              </div>
            </el-upload>
          </el-col>
        </el-row>
        <el-form-item label="邮箱" prop="email">
          <el-input placeholder="请输入邮箱" v-model="memberModel.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input placeholder="请输入手机号" v-model="memberModel.phone"></el-input>
        </el-form-item>
        <el-form-item label="会员属性" prop="membershipType">
          <el-radio-group v-model="memberModel.membershipType" class="membership-radio">
            <el-radio label="VIP">VIP</el-radio>
            <el-radio label="普通">普通</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="status-radio-group">
          <el-radio-group v-model="memberModel.status">
            <el-radio-button label="在会" value="1" />
            <el-radio-button label="退会" value="0" />
          </el-radio-group>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="doSubmit" class="dialog-btn confirm">确定</el-button>
          <el-button @click="memberDlgShow=false" class="dialog-btn cancel">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<style scoped>
.member-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 搜索区域样式 */
.search-card {
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  margin-bottom: 15px;
}

.search-input, .search-select, .search-date {
  transition: all 0.3s ease;
}

.search-input:focus-within, .search-select:focus-within, .search-date:focus-within {
  box-shadow: 0 0 0 2px rgba(145, 163, 255, 0.2);
}

/* 操作按钮区域 */
.action-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.action-btn {
  transition: all 0.2s ease;
  border-radius: 4px;
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.add-btn {
  background-color: #409eff;
}

.edit-btn {
  background-color: #67c23a;
}

.delete-btn {
  background-color: #f56c6c;
}

.search-btn {
  background-color: #1890ff;
}

.reset-btn {
  background-color: #909399;
}

/* 表格区域样式 */
.table-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  margin-bottom: 15px;
}

.table-grid {
  margin-top: 0;
  border: none;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

.el-table tr:hover > td {
  background-color: #f0f7ff !important;
}

.tableRowClassName {
  transition: background-color 0.2s ease;
}

/* 表格内标签样式 */
.gender-tag, .vip-tag, .normal-tag, .status-tag {
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 12px;
}

.male {
  background-color: #e6f7ff;
  color: #1890ff;
  border-color: #91a3ff;
}

.female {
  background-color: #fff0f0;
  color: #f56c6c;
  border-color: #f56c6c;
}

.vip-tag {
  background-color: #fff2e8;
  color: #fa541c;
  border-color: #fa541c;
}

.normal-tag {
  background-color: #f0f2f5;
  color: #4e5969;
  border-color: #dcdfe6;
}

.status-tag.active {
  background-color: #f6ffed;
  color: #52c41a;
  border-color: #52c41a;
}

.status-tag.inactive {
  background-color: #fff1f0;
  color: #ff4d4f;
  border-color: #ff4d4f;
}

/* 表格操作按钮 */
.table-btn {
  border-radius: 4px;
  margin: 0 3px;
  transition: all 0.2s ease;
}

.table-btn.edit {
  background-color: #409eff;
  border-color: #409eff;
}

.table-btn.delete {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.table-btn:hover {
  transform: scale(1.05);
}

/* 分页区域 */
.pagination-container {
  background: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.member-pi {
  margin-top: 0;
  text-align: right;
}

/* 头像样式 */
.rowImg {
  width: 60px;
  height: 60px;
  border-radius: 50%; /* 圆形头像 */
  background-size: cover; /* 覆盖方式显示，保持比例 */
  background-repeat: no-repeat;
  background-position: center;
  border: 2px solid #f0f0f0; /* 浅色边框 */
  box-shadow: 0 2px 4px rgba(0,0,0,0.1); /* 轻微阴影 */
  transition: transform 0.2s ease;
}

.rowImg:hover {
  transform: scale(1.05); /* 悬停放大效果 */
}

/* 对话框样式 */
.member-dialog {
  border-radius: 8px;
  overflow: hidden;
}

.member-form {
  margin-top: 15px;
}

/* 头像上传区域 */
.avatar-uploader {
  width: 160px;
  height: 160px;
  margin-left: 25px;
  position: relative;
}

.avatar-uploader:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.avatar-img {
  width: 160px;
  height: 160px;
  border-radius: 8px; /* 圆角矩形 */
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
  border: 1px solid #e4e4e4;
  transition: all 0.3s ease;
}

.uploaded-avatar:hover .avatar-overlay {
  opacity: 1; /* 悬停显示覆盖层 */
}

.edit-icon {
  color: white;
  font-size: 24px;
}

/* 未上传时的占位样式 */
.avatar-placeholder {
  width: 160px;
  height: 160px;
  border-radius: 8px;
  border: 2px dashed #dcdfe6; /* 虚线边框 */
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  transition: all 0.3s ease;
}

.avatar-placeholder:hover {
  border-color: #409eff; /* 悬停时边框变主题色 */
  color: #409eff;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

/* 单选按钮组样式 */
.gender-radio, .membership-radio {
  display: flex;
  gap: 15px;
}

.status-radio-group {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 对话框按钮 */
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.dialog-btn {
  width: 100px;
  transition: all 0.2s ease;
}

.dialog-btn.confirm {
  background-color: #409eff;
  border-color: #409eff;
}

.dialog-btn.cancel {
  background-color: #f5f5f5;
  color: #333;
}

.dialog-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 动画效果 */
.el-button, .el-input, .el-select, .el-date-picker, .el-table, .el-dialog {
  transition: all 0.2s ease-in-out;
}

.el-table__row {
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(5px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>

<script setup>
// 原有脚本代码保持不变
import {onMounted, ref, reactive, toRaw, nextTick} from "vue"
import api from "@/util/api"
import {Avatar, CirclePlus, Delete, Edit, Plus, RefreshRight, Search} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {cloneDeep} from "lodash";
import baseUrl from "@/util/constant.js";
import {getJwt} from "@/api/jwt.js";

onMounted(async () => {
  searchAll();
});

let members = ref();
let memberPi = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0
});
let memberSearchModel = ref({
  name: null,
  gender: null,
  birthdayRange: []
});
let memberSearchForm = ref();
let memberDlgTitle = ref("新增会员");
let memberDlgShow = ref(false);

let memberModel = ref({
  name: null,
  gender: null,
  birthDate: null,
  joinDate: null,
  email: null,
  phone: null,
  membershipType: null,
  balance: null,
  status: null,
  avatar: null,
})

let mode = "add";
let tblRef = ref();

const headers={
  "jwt":getJwt()
}

async function searchAll(pageNo = 1, pageSize = 10) {
  let params = toRaw(memberSearchModel.value);
  if (params.birthdayRange && params.birthdayRange.length === 2) {
    params.birthdayFrom = params.birthdayRange[0];
    params.birthdayTo = params.birthdayRange[1];
    delete params.birthdayRange;
  }

  params.deleted = 1;
  let resp = await api({
    url: "/members",
    method: "get",
    params: {
      pageNo,
      pageSize,
      ...params
    }
  });
  console.log(resp);
  members.value = resp.data.records;
  memberPi.pageSize = resp.data.size;
  memberPi.total = resp.data.total;
  memberPi.pageNo = resp.data.current;
}

function memberPiChange(pageNo, pageSize) {
  searchAll(pageNo, pageSize);
}

function reset() {
  memberSearchForm.value.resetFields();
  searchAll();
}

function tblRowClick(row) {
  tblRef.value.toggleRowSelection(row);
}

function remove() {
  let rows = tblRef.value.getSelectionRows();
  if (rows === null || rows.length === 0) {
    ElMessage({
      message: '请选中要删除的数据',
      type: 'warning',
    })
  } else {
    ElMessageBox.confirm(
        '是否确认删除',
        '警告',
        {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }
    ).then(() => {
      let ids = rows.map(row => row.id)
      removeByIds(ids);
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    })
  }
}
function removeRow(row) {
  ElMessageBox.confirm(
      '是否确认删除',
      '警告',
      {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      }
  ).then(() => {
    removeByIds([row.id]);
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除',
    })
  })
}

async function removeByIds(ids) {
  let resp = await api({
    url: "/members/deleted",
    method: "put",
    data: {
      ids,
      deleted: 0
    }
  });
  if (resp.success) {
    ElMessage.success("删除成功,共删除" + resp.data + "条数据")
    searchAll();
  } else {
    ElMessage({
      type: 'info',
      message: '删除失败',
    })
  }
}

function add() {
  memberDlgTitle.value = "新增会员";
  memberDlgShow.value = true;
  mode = "add";
  memberModel.value = {
    name: null,
    gender: '男',
    birthDate: null,
    joinDate: null,
    email: null,
    phone: null,
    membershipType: '普通',
    balance: null,
    status: null,
    avatar: null,
    deleted: 1
  }
}

function doSubmit() {
  if (mode === "add") {
    submitAdd();
  } else {
    submitEdit();
  }
}

function submitAdd() {
  let params = toRaw(memberModel.value);
  if (params.gender === '男') {
    params.gender = 'M';
  } else if (params.gender === '女') {
    params.gender = 'F';
  }
  memberForm.value.validate(valid => {
    if (valid) {
      let resp = api({
        url: "/members",
        method: "post",
        data: params
      }).then(resp => {
        if (resp.success) {
          console.log(resp)
          memberDlgShow.value = false;
          searchAll();
          ElMessage.success("新增成功")
        } else {
          ElMessage.error(resp.msg || "新增失败")
        }
      }).catch(resp => {
        ElMessage.error(resp.msg || "新增失败")
      });
    } else {
      ElMessage.error("请填写必填项")
    }
  })
}

let memberForm = ref();

function resetMemberForm() {
  memberForm.value.resetFields();
}

function edit() {
  let rows = tblRef.value.getSelectionRows();
  if (rows === null || rows.length === 0) {
    ElMessage.warning("请选择要修改的行");
  } else if (rows.length > 1) {
    ElMessage.warning("只能选择一行进行修改");
  } else {
    memberDlgShow.value = true;
    memberDlgTitle.value = "修改会员信息";
    mode = "edit";
    nextTick(() => {
      memberModel.value = cloneDeep(toRaw(rows[0]));
      if (memberModel.value.gender === 'M') {
        memberModel.value.gender = '男';
      } else if (memberModel.value.gender === 'F') {
        memberModel.value.gender = '女';
      }
      memberModel.value.status = memberModel.value.status === 1 ? "1" : "0";
    });
  }
}

async function submitEdit() {
  let params = toRaw(memberModel.value);
  if (params.gender === '男') {
    params.gender = 'M';
  } else if (params.gender === '女') {
    params.gender = 'F';
  }
  let resp = await api({
    url: "/members",
    method: "put",
    data: params
  });
  console.log("========"+resp);
  if (resp.success) {
    memberDlgShow.value = false;
    searchAll(memberPi.pageNo, memberPi.pageSize);
    ElMessage.success("修改成功")
  }
}

function editRow(row) {
  memberDlgShow.value = true;
  memberDlgTitle.value = "修改会员信息";
  mode = "edit";
  nextTick(() => {
    memberModel.value = cloneDeep(toRaw(row))
    if (memberModel.value.gender === 'M') {
      memberModel.value.gender = '男';
    } else if (memberModel.value.gender === 'F') {
      memberModel.value.gender = '女';
    }
    memberModel.value.status = memberModel.value.status === 1 ? "1" : "0";
  });
}

const rules = {
  name: [
    {required: true, message: '请输入会员名称', trigger: 'blur'},
    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
    {min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur'},
    {validator: validatePhone, trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱地址', trigger: 'blur'},
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
  ]
}

function validatePhone(rule, value, callback) {
  if (value.startsWith("1")) {
    return callback();
  } else {
    return callback(new Error('请输入格式正确的手机号码'));
  }
}

function handleAvatarSuccess(resp) {
  memberModel.value.avatar = resp.data;
}

// 用于表格行样式的回调函数
function tableRowClassName({row, rowIndex}) {
  return 'tableRowClassName';
}

// 头像上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/gif'|| file.type === 'image/jpg';
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isJPG) {
    ElMessage.error('只能上传JPG/PNG/GIF格式的图片!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!');
    return false;
  }
  return true;
};
</script>